<?php
    require_once '../../init.php';
    
    header("Access-Control-Allow-Origin:*");
    $APIURL=$_SERVER['REQUEST_URI'];
    $APIURL=explode("?",$APIURL);
    $request=[];
    if(@$APIURL[1]){
        $request=explode("/",$APIURL[1]);
        // ajaxReturn (404,"图片有误",$request); 
    }
    $urlOrigin=[
        "isopen"=>true,
        "isnotreferer"=>false,
        "whiteLst "=>["xrdv.cn","kingmin.cn","xkji.cn","localhost"], 
        "defaultImg"=>"",
    ];
    if($urlOrigin['isopen']){
        @$referer=isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $defaultImg=$urlOrigin['defaultImg']?$urlOrigin['defaultImg']:imgUrlpd("/content/images/icon/defaultImg.png");
        if($referer){
            $refererhost=parse_url($referer);
            $host = strtolower($refererhost['host']);
            if(!in_array($host, $urlOrigin['whiteLst'])){
                img($defaultImg,0);exit;
            }
        }else{
            if($urlOrigin['isnotreferer']){
                img($defaultImg,0);exit;
            }
        }
    }
    // ajaxReturn (404,"图片有误",$referer); 
    $APIURL=explode("/",$APIURL[0]);
    @$imgid=$APIURL[3];
    @$imgfbl=0;//$APIURL[4];
    if(!intval($imgid)){
        ajaxReturn (404,"图片有误",$APIURL); 
    }
    if(!$imgfbl){
        $imgfbl=5;
    }
    $shuiyin=[
            'isopen'=>true,
            'text'=>"KMLOVE",
            'color'=>'rgb(125,125,125)',
            'dissolve'=>100,
            'size'=>40,
            
            
        ];
    // ajaxReturn (202,'',$APIURL); 
    $imgs=imagesdetails($imgid);
    if(@!$imgs){
        ajaxReturn (404,"图片不存在",$APIURL);  
    }
    if(@$imgs['isdel']=='0'){
        if($request[0]){
        }
        if(@$imgs['type']=='1'){
            $imgurl=$imgs['url'];
            if($imgs['isuptp']=='1'){
                
                $img=$_SERVER['DOCUMENT_ROOT'].$imgs['remark']['path'];
                // echo 
                foreach ($request as $k => $v){
                    if($v=='quality'){
                        @$imgfbl=intval($request[$k+1]);
                    }
                    if(@$v=='info'){
                        $imgs['info']["quality"]= $imgfbl;
                       ajaxReturn (200,"获取详情成功",$imgs['info']); 
                    }
                    if(@$v=='watermark'){
                        $img =attach_text_logo($img, $shuiyin['text'],$shuiyin['size']);
                        ob_clean();
                        shuiyinimg($img,$imgfbl);exit;
                    }
                }
                // return false;
                if(@$request[0]=='watermark'){
                    $img =attach_text_logo($img, $shuiyin['text'],$shuiyin['size']);
                }
                // ajaxReturn (200,"获取详情成功",$imgfbl); 
                img($img,$imgfbl);exit;
            }else{
                if(@$request[0]=='watermark'){
                   $text=$shuiyin['text'];
                   $size=intval($shuiyin['size'])/0.05;
                   $imgurl.="?watermark/2/text/".urlsafe_b64encode($text)."/font/".urlsafe_b64encode('宋体')."/fontsize/$size/fill/".urlsafe_b64encode($shuiyin['color'])."/dissolve/".$shuiyin['dissolve']."/rotate/30/uw/180/uh/180/resize/1";
                }else{
                    if($imgfbl<9){
                        $quality=$imgfbl*10;
                    }
                    if($imgfbl==9){
                        $quality=100;
                    }
                    $imgurl.="?imageView2/2/w/375/q/$quality";
                }
                header("Location: $imgurl");
            }
        }else{
            header("Location: ".$imgs['url']);
        }
    }else{
       ajaxReturn (404,"文件已被删除",$APIURL);  
    }
    
    // 获取图片详情
    function imagesdetails($id){
        $db = Database::getInstance();
        
        $sql = "SELECT * FROM `" . DB_PREFIX . "sys_upload` WHERE `id`='$id' ;";
        $logs = $db->query($sql);
        
        $data = array();
        $login= new LoginAuth();
        foreach ($logs as $key => $v) {
            $v['remark']=json_decode($v['remark'],true);
            if($v['type']=='1'){
                $v['info']=[
                    "size"=>$v['fsize'],
                    "format"=>$v['remark']['format'],
                    "width"=>intval($v['remark']['width']),
                    "height"=>intval($v['remark']['height'])
                ];
            }
            $data=$v;
        }
        
        return $data;
    }
    
    function urlsafe_b64encode($string) {

        $data = base64_encode($string);
        
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        
        return $data;
        
    }
    
    // 输出图片
    function img($img,$quality=0){
        ob_clean();/* 清空(擦掉)输出缓冲区，不加此行可能无法显示图像*/
        // ajaxReturn (404,"图片有误".$quality,$img); 

        $source =  '001.jpeg';  
        $dst_img = '001_new.jpeg';  
        $percent = 1;  #原图压缩，不缩放，但体积大大降低  
        if($quality>0){
            $quality=$quality/10;
        }else{
           $quality=1; 
        }
        $image = (new imgcompress($img,$quality))->compressImg();
        exit;
    }
    function shuiyinimg($img,$quality=0){
        $img = $img;
        @$info = getimagesize($img);
        if(!$info){
            ajaxReturn (404,"图片有误",$img); 
        }
        $imgExt = image_type_to_extension($info[2], false);  //获取文件后缀
        $fun = "imagecreatefrom{$imgExt}";
        $imgInfo = $fun($img);                     //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
        //$mime = $info['mime'];
        // $mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
        $mime = "image/png";//image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
        // ajaxReturn (404,"图片已被删除",$mime);  
        header('Content-Type:'.$mime);
        if($imgExt == 'png')// $quality = 9;        //输出质量,JPEG格式(0-100),PNG格式(0-9)
        {
            if($quality>9){
                $quality=9;
            }
        }else{
            if($quality<9){
                $quality=$quality*10;
            }
            if($quality==9){
                $quality=100;
            }
        }
        $getImgInfo = "image{$imgExt}";
        $getImgInfo($imgInfo, null, $quality);    //2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
        // ajaxReturn (404,"图片已被删除",$getImgInfo);
        // ob_clean();/* 清空(擦掉)输出缓冲区，不加此行可能无法显示图像*/
        imagedestroy($imgInfo);
    }
    
    // 图片水印
    
    function attach_text_logo($imgFilePath, $textLogo,$textSize="") {
        //创建图片的实例
        $im = imagecreatefromstring(file_get_contents($imgFilePath));
        list($width, $height, $type, $attr) = getimagesize($imgFilePath);
     
        // 水印字体颜色
        $textColor = imagecolorallocate($im, 125, 125, 125);
        // 水印字体大小
        if(!$textSize){
            $textSize = 30;
        }
        
        // 下载地址（放到本地）：https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf
        $fontFile = PASH_ROOT."/content/fonts/kaiti.ttf";;
        
        $temp = imagettfbbox($textSize,0,$fontFile,$textLogo);
		$w = $temp[2] - $temp[6];
		$h = $temp[3] - $temp[7];
        // ajaxReturn (404,"图片有误",$temp); 
        // 添加文字水印
        imagefttext($im, $textSize, 0, $width - $w - 20, $height - $h + 10, $textColor, $fontFile, $textLogo);
     
        // 保存文件 git/jpg/png/bmp
        $savePath = tempnam("/tmp", "pic");
        switch($type)
        {
        case 1:
            imagegif($im, $savePath);
            break;
        case 2:
            imagejpeg($im, $savePath);
            break;
        case 3:
            imagepng($im, $savePath);
            break;
        case 6:
            imagewbmp($im, $savePath);
            break;
        default:
            imagepng($im, $savePath);
        }
     
        imagedestroy($im);
     
        return $savePath;
    }
?>